import http from '../../request/api';
const state = {
    registerType: 'online',//online|offline
    userInfo: {}
}

const getters = {
}

const mutations = {
    setUserInfo(state, v) {
        state.userInfo = v
    },
    setRegisterType(state, v) {
        state.registerType = v
    },
}
const actions = {
    login: ({ commit, dispatch }, isFromBook) => {
        if (isFromBook) {
            commit('setRegisterType', 'offline');
        } else {
            commit('setRegisterType', 'online');
        }
        console.log('isFromBook', isFromBook);

        return new Promise((r) => {
            let token = uni.getStorageSync('token');
            if (token) {
                commit('setUserInfo', uni.getStorageSync('userInfo'));
                if (!isFromBook) {
                    dispatch('isWorker');
                }
                r();
            } else {
                uni.login({
                    provider: 'weixin',
                    success: (res) => {
                        http.wxLogin({
                            code: res.code
                        }).then(data => {
                            console.log("login", data);
                            if (data) {
                                token = data.token;
                                uni.setStorageSync('token', token);
                                uni.setStorageSync('userInfo', data);
                                commit('setUserInfo', data)
                                if (!isFromBook) {
                                    dispatch('isWorker');
                                }
                            }
                            r();
                        })
                    }
                });
            }
        })
    },
    isWorker: () => {
        // 判断用户身份是否为工作人员
        http.getWorkToken().then(res => {
            console.log('getWorkToken', res.work_token);
            if (res.work_token) {
                uni.setStorageSync('workToken', res.work_token);
                // 核销员
                uni.navigateTo({
                    url: '/packageA/check/check',
                });
            } else {
                // 顾客
                uni.switchTab({
                    url: '/pages/home/home',
                });
            }
        });
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}